<template>
    <div class="login-from">
        <van-form @submit="onSubmit">
            <van-cell-group inset>
                <van-field name="nickName" label="昵称" placeholder="请填写昵称"
                    v-if="!select"
                    v-model="nickName"
                    :rules="[{ 
                        required: true, 
                        message: '不合法，请重新输入'
                    }]"
                />
                <van-field name="tel" label="手机号" placeholder="请填写手机号"
                    v-model="tel"
                    :rules="[{ 
                        required: true, 
                        pattern: telPattern, 
                        message: '不合法，请重新输入',
                    }]"
                />
                <van-field type="password" name="password" label="密码" placeholder="请填写6-8位密码"
                    v-model="password"
                    :rules="[{
                        required: true,
                        pattern: passwordPattern,
                        message:'不合法，请重新输入（不能包含数字字母下划线）',
                    }]"
                />
            </van-cell-group>
            <div style="margin: 1rem">
                <van-button round block type="primary" native-type="submit"
                    @click="select ? handleLogin() : handleSignup()"
                >
                    {{ select ? "登录" : "注册" }}
                </van-button>
            </div>
        </van-form>
    </div>
</template>

<script>
    import { mapActions, mapMutations } from "vuex";
    import { eventBus, eventTypes } from "@/utils/event-bus";
    import { Toast } from "vant";

    export default {
        props: ["select", "initApp"],
        data() {
            return {
                nickName: "",
                tel: "",
                password: "",
                telPattern: /1\d{10}/,
                passwordPattern: /\w{6,8}/,
            };
        },
        methods: {
            ...mapMutations(['upUser']),
            ...mapActions('login', ['signup', 'login']),
            onSubmit() {
                Toast.loading({
                    message: "加载中...",
                    forbidClick: true,
                    duration: 0,
                });
            },
            async handleSignup() {    // 注册
                let res = await this.signup({ nickName: this.nickName, phone: this.tel, password: this.password });
                eventBus.emit(eventTypes.INITAPP, res);
                // this.initApp(res);
            },
            async handleLogin() {     // 登录
                let res = await this.login({ phone: this.tel, password: this.password });
                // this.initApp(res);
                eventBus.emit(eventTypes.INITAPP, res);
            },
        },
    };
</script>